package org.example.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.dto.GradeDto;
import org.example.service.GradeService;
import org.example.service.TestService;
import org.example.utils.JsonUtils;
import org.example.vo.GradeVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Rongchang Wu
 * @version 1.0
 * @description: TODO
 * @date 2021/12/8 17:30
 */
@RestController
public class GradeController {
    @Resource
    GradeService service;

    @GetMapping("/getGradeList")
    public void getGradeList(HttpServletResponse resp, Integer page, Integer limit) throws IOException {
        Page<Object> obj = PageHelper.startPage(page, limit);
        List<GradeDto> gradeList = service.queryAllGrade();
        Integer count = service.countGrade();
        //以上调用service获取专业数据和数量

        JsonUtils.customJson(resp, gradeList, count);
    }

    @GetMapping("/getGradeByDepartmentNameAndMajorName")
    public void getGradeByDepartmentNameAndMajorName(HttpServletResponse resp, String departmentName, String majorName, Integer page, Integer limit) throws IOException {
        Page<Object> obj = PageHelper.startPage(page, limit);
        List<GradeDto> gradeList = service.queryGradeByDepartmentAndMajor(departmentName, majorName);
        Integer count = service.countGradeByDepartmentAndMajor(departmentName, majorName);

        JsonUtils.customJson(resp, gradeList, count);
    }

    @GetMapping(value = "/deleteGrade", produces = "text/plain;charset=utf-8")
    public String deleteGrade(String gradeId) {
        String[] gradeIds = gradeId.split(",");
        Integer status = 0;
        for (int i = 0; i < gradeIds.length; i++) {
            status += service.deleteGrade(Integer.parseInt(gradeIds[i]));
        }

        return status > 0 ? "success" : "error";
    }

    @GetMapping(value = "/addGrade", produces = "text/plain;charset=utf-8")
    public String addGrade(GradeVo grade) {
        Integer status = service.addGrade(grade);

        return status > 0 ? "success" : "error";
    }

    @GetMapping(value = "/getGradeById")
    public GradeDto getGradeById(Integer gradeId) {
        System.out.println("gradeId= " + gradeId);
        GradeDto grade = service.queryGradeById(gradeId);

        return grade;
    }

    @GetMapping(value = "/editGrade")
    public String editGrade(GradeVo grade) {
        Integer status = service.updateGrade(grade);

        return status > 0 ? "success" : "error";
    }
}
